package com.dhcc.core.modules.common.controller;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.dhcc.core.config.properties.SysProperties;
import com.dhcc.core.framework.base.controller.BaseController;
import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.exception.BizExceptionEnum;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.util.ArrayUtil;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.FileUtil;
import com.dhcc.core.framework.util.PinyinUtil;
import com.dhcc.core.modules.common.entity.FileEntity;
import com.google.common.collect.Lists;

/**
 * 文件控制器
 * 
 * @ClassName: ImageManagerController
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午10:18:51
 */
@Controller
@RequestMapping("/imagemanager")
public class ImageManagerController extends BaseController {

    @Autowired
    private SysProperties sysProperties;

    /**
     * 管理页
     */
    @RequestMapping
    public String index(@RequestParam(value = "path", required = false) String path,
            @RequestParam(value = "target", required = false) String target,
            @RequestParam(value = "thumb", required = false) String thumb,
            @RequestParam(value = "filterName", required = false) String filterName, Model model) {
        String absolutePath = sysProperties.getFileUploadPath();
        String parentPath = "imagemanager";
        if (CommonUtil.isEmpty(path)) {
            path = parentPath;
        } else {
            String[] _array = ArrayUtil.stringToArray(path, "/");
            for (int i = 0; i < (_array.length - 1); i++) {
                if (i == 0) {
                    parentPath = _array[i];
                } else {
                    parentPath += "/" + _array[i];
                }
            }
        }

        absolutePath = absolutePath + path;
        List<FileEntity> result = Lists.newArrayList();
        File mainFile = new File(absolutePath);
        if (!mainFile.exists()) {
            mainFile.mkdirs();
        }
        for (File file : mainFile.listFiles()) {
            if (CommonUtil.isEmpty(filterName) || file.getName().indexOf(filterName) > -1) {
                FileEntity templateFile = new FileEntity();
                templateFile.setFileName(file.getName());
                templateFile.setFilePath(path + "/" + file.getName());
                templateFile.setIsDirectory(file.isDirectory());
                result.add(templateFile);
            }
        }
        model.addAttribute("fileList", result);
        model.addAttribute("currentPath", path);
        model.addAttribute("parentPath", parentPath);
        model.addAttribute("target", target);
        model.addAttribute("thumb", thumb);
        model.addAttribute("filterName", filterName);
        return "/imagemanager.html";
    }

    /**
     * 上传文件
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public R handleFileUpload(@RequestParam(value = "path", required = true) String path, HttpServletRequest request) {
        String fileSavePath = sysProperties.getFileUploadPath();
        if (CommonUtil.isEmpty(path)) {
            path = "imagemanager";
        }
        fileSavePath = fileSavePath + path;

        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file[]");
        File dir = new File(fileSavePath);
        if (!dir.exists()) {
            throw new BizException("请确认上传的目录!");
        }
        for (MultipartFile file : files) {
            String fileName = PinyinUtil.convert(file.getOriginalFilename());
            try {
                file.transferTo(new File(fileSavePath + File.separator + fileName));
            } catch (Exception e) {
                throw new BizException(BizExceptionEnum.UPLOAD_ERROR);
            }
        }
        return R.ok();
    }

    /**
     * 新建文件夹
     */
    @RequestMapping(method = RequestMethod.POST, path = "/folder")
    @ResponseBody
    public R folder(@RequestParam(value = "path", required = true) String path,
            @RequestParam(value = "folder", required = true) String folder) {
        String fileSavePath = sysProperties.getFileUploadPath();
        if (CommonUtil.isEmpty(path)) {
            path = "imagemanager";
        }
        fileSavePath = fileSavePath + path;

        folder = PinyinUtil.convert(folder);
        File dir = new File(fileSavePath + File.separator + folder);
        if (!dir.exists()) {
            dir.mkdirs();
        } else {
            throw new BizException("文件夹已存在！");
        }
        return R.ok();
    }

    /**
     * 删除文件
     */
    @RequestMapping(method = RequestMethod.POST, path = "/delete")
    @ResponseBody
    public R delete(@RequestParam(value = "path", required = true) String[] path) {
        String absolutePath = sysProperties.getFileUploadPath();
        if (CommonUtil.isEmpty(path)) {
            throw new BizException("未选择文件！");
        }
        for (String _path : path) {
            File _file = new File(absolutePath + _path);
            if (!_file.exists()) {
                throw new BizException("文件不存在！");
            } else {
                FileUtil.deleteFile(_file);
            }
        }
        return R.ok();
    }
}
